<?php
/**
  * IBD - Projet Helvetia - 2009
  *
  * Alexandre DOS SANTOS COELHO
  * Mathieu RICHARD
  * Karim EL-ALAILI
  * Julien REBETEZ
  *
  */

/**
 * Modele pour un utilisateur
 * @package modeles
 */
class User extends AppModel
{
  var $name = 'User';
  var $belongsTo = 'Group';

  var $validate = array(
        'username' => array(
                        array('rule' => 'isUnique', 'message' => 'Deja utilise'),
                        array('rule' => array('between', 1, 20), 'message' => 'Minimum 1 caractere')),
        'password' => array('rule' => array('between', 6, 20), 'message' => 'Minimum 6 caracteres'),
        'first_name' => array('rule' => array('minLength', 1), 'message' => 'Ne peut pas etre vide'),
        'last_name' => array('rule' => array('minLength', 1), 'message' => 'Ne peut pas etre vide')
      );

  function afterFind ($results) 
  {
    foreach ($results as $key => $val) 
      $results[$key]['User']['password'] = '';
    
    return $results;
  }

  function beforeSave ()
  {
    $pass = $this->data['User']['password'];
    $this->data['User']['password'] = md5($pass);

    return true;
  }

  /**
   * Fonction testant si $data correspond a un couple username/password correct
   * @param $data le couple a tester
   * @return true si l'authentification est reussi, false sinon
   */
  function validateLogin ($data)
  {
    $user = $this->find(array('username' => $data['username'],
                              'password' => md5($data['password'])),
                        array('id', 'username'));
    if (!empty($user))
      return $user['User'];
    return false;
  }
}
